package org.example;

import com.ververica.cdc.connectors.mysql.table.StartupOptions;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import com.ververica.cdc.debezium.JsonDebeziumDeserializationSchema;
import com.ververica.cdc.connectors.mysql.source.MySqlSource;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;

public class MySqlSourceExample {
    public static void main(String[] args) throws Exception {
        MySqlSource<String> mySqlSource = MySqlSource.<String>builder()
                .hostname("localhost")
                .port(3306)
                .databaseList("erp") // set captured database, If you need to synchronize the whole database, Please set tableList to ".*".
                .tableList("erp.visit_info", "erp.erp_timing_device_open") // set captured table
                .username("root")
                .password("123456")
                .startupOptions(StartupOptions.initial())
                .deserializer(new JsonDebeziumDeserializationSchema()) // converts SourceRecord to JSON String
                .build();

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        // enable checkpoint
        env.enableCheckpointing(10000);

        long startTime = System.currentTimeMillis();
        DataStreamSource<String> mysqlSource = env.fromSource(mySqlSource, WatermarkStrategy.noWatermarks(), "MySQL Source")
                .setParallelism(5);
        mysqlSource.print("mysqlSource====");

//        mysqlSource.filter(s -> s.contains("\"op\":\"u\""))
//                .addSink(new SinkFunction<String>() {
//                    @Override
//                    public void invoke(String value, Context context) throws Exception {
//                        System.out.println(value);
//                        System.out.println("time: " + (System.currentTimeMillis() - startTime) + "ms");
//                    }
//                })
//                .setParallelism(1); // use parallelism 1 for sink to keep message ordering

        env.execute("Print MySQL Snapshot + Binlog");
    }
}